package servlet;

import java.sql.Date;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Quest;
import DAO.QuestDao;
import DAO.UserDetailDao;

public class QuestModifyAction implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Quest quest = new Quest();
		QuestDao questDao = new QuestDao();
		
		HttpSession session=request.getSession();
		UserDetailDao userDetailDao = new UserDetailDao();
		ActionForward forward=new ActionForward();
		
			
		int studyId = request.getParameter("studyId") != null
				&& request.getParameter("studyId") != "" ? Integer
				.parseInt(request.getParameter("studyId")) : 0;
		int userId = session.getAttribute("userid") != null
				&& session.getAttribute("userid") != "" ? Integer
				.parseInt((String)session.getAttribute("userid")) : 0;
				int questId = request.getParameter("questId") != null
						&& request.getParameter("questId") != "" ? Integer
							.parseInt(request.getParameter("questId")) : 0;		
				
				
		System.out.println(userId +" " + studyId);
		if (userId < 1) {
			session.invalidate();
			Util.ShowError(response, "로그인해주세요");
		}
		if (studyId < 1) {
			Util.ShowError(response, "잘못 된 접근입니다");
		}
		request.setAttribute("studyId", studyId);	
		
		String title = request.getParameter("title")!= null && request.getParameter("title") 
				!= ""? request.getParameter("title") : null;	
		String content = request.getParameter("content")!= null && request.getParameter("content") 
				!= ""? request.getParameter("content") : null;		
		Date expiredTime = request.getParameter("expiredtime")!= null&& request.getParameter("expiredTime") 
				!= "" ? Date.valueOf(request.getParameter("expiredtime")) : null;
		
		Timestamp expiredTimeStamp = new Timestamp(expiredTime.getTime());
				
				
		System.out.println("expiredTime " + expiredTime );		
		if(content==null || expiredTime==null || title==null)  {
			//error return
			Util.ShowError(response, "값을 올바로 입력해주세요");
			
			return null;
		}

		title=Util.toUTF8(title);
		content=Util.toUTF8(content);
		
		quest.setQuestId(questId);
		quest.setSid(studyId);
		quest.setUid(userId);
		quest.setTitle(title);
		quest.setContent(content);
		quest.setExpiredTime(expiredTimeStamp);
	
		questDao.updateQuestInfo(quest);
	
		
	
		// go to details studyId;
		
		forward.setPath("./study_quest.jsp");

		return forward;
	}
}
